package com.ga.service;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadService {
	public static UploadService instance=new UploadService();
	
	public String upload(int maxMemSize,int maxFileSize,String fname,String filePath,HttpServletRequest request){
		String fileName ="";
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 设置内存中存储文件的最大值
			factory.setSizeThreshold(maxMemSize);
			// 本地存储的数据大于 maxMemSize.
			factory.setRepository(new File("c:\\temp"));
			// 创建一个新的文件上传处理程序
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 设置最大上传的文件大小
			upload.setSizeMax(maxFileSize);
				// 解析获取的文件
				List<FileItem> fileItems = upload.parseRequest(request);
				// 处理上传的文件
				Iterator<FileItem> i = fileItems.iterator();
				while (i.hasNext()) {
					FileItem fi = (FileItem) i.next();
					if (!fi.isFormField()) {
						// 获取上传文件的参数
					    fileName = fi.getName();
						fileName=fname+fileName.substring(fileName.indexOf("."));
						// 写入文件
						File file = new File(filePath +fileName);
						fi.write(file);
					}
				}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fileName;
	
	}
}
